package sicnu.cs.ich.security.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import sicnu.cs.ich.api.domain.form.RoleForm;
import sicnu.cs.ich.common.exceptions.exception.BusinessException;
import sicnu.cs.ich.security.domain.entity.Permission;
import sicnu.cs.ich.security.domain.entity.Role;
import sicnu.cs.ich.security.mapper.RoleMapper;
import sicnu.cs.ich.security.mapper.UserMapper;
import sicnu.cs.ich.security.service.IPermissionService;
import sicnu.cs.ich.security.service.IRoleService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/12/7-18:50
 **/
@RequiredArgsConstructor
@Service
@Slf4j
public class RoleServiceImpl implements IRoleService {
    private final RoleMapper roleMapper;
    private final UserMapper userMapper;
    private final IPermissionService permissionService;
    @Override
    public Role getRole(Integer roleId) {
        Role role = roleMapper.selectById(roleId);
        if (role==null){
            throw new NoSuchElementException("无效角色");
        }
        return role;
    }

    @Override
    public List<Role> getUserRole(Integer userId) {
        var roles = roleMapper.findRolesByUserid(userId);
        if (CollectionUtils.isEmpty(roles)){
            throw new BusinessException("用户无角色信息");
        }
        return new ArrayList<>(roles);
    }

    /**
     * 获取角色信息
     */
    @Override
    public List<Role> getRoles() {
        return roleMapper.findRoles();
    }

    /**
     * 添加新角色
     *
     * @param roleForm 角色
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class,propagation = Propagation.REQUIRED)
    public boolean addRole(RoleForm roleForm) {
        var permissions = permissionService.getPermissions();
        HashMap<Integer, Permission> map = permissions.stream().collect(HashMap::new, (m, e) -> m.put(e.getId(), e), HashMap::putAll);
        //var map = permissions.stream().collect(Collectors.groupingBy(PermissionVo::getId));
        var set = Arrays.stream(roleForm.getPermissionId()).collect(Collectors.toSet());
        for (Integer permissionId : set) {
            var permission = map.get(permissionId);
            // 没有找到对应的权限
            if (permission == null){
                return false;
            }
            // 传入的权限无父级id
            if (permission.getParentId()!=0&&!set.contains(permission.getParentId())){
                return false;
            }
        }
        // 校验通过
        if (roleMapper.addRole(roleForm)>0) {
            if (roleMapper.addPermission(roleForm.getRoleId(),set.toArray(Integer[]::new))>0) {
                return true;
            }
        }
        throw new BusinessException("新增失败");
    }

    /**
     * 判断角色是否存在
     *
     * @param role 角色名
     */
    @Override
    public boolean isRoleExisted(String role) {
        return roleMapper.countRole(role)>0;
    }

    /**
     * 删除角色信息
     * 关联角色置为ROLE_PERSON
     */
    @Transactional(rollbackFor = RuntimeException.class,propagation = Propagation.REQUIRED)
    @Override
    public boolean deleteRole(Integer roleId) {
        var list = userMapper.findUserIdByRole(roleId);
        // 删除并重新插入用户数据
        if(!CollectionUtils.isEmpty(list)){
            // 删除用户对应的角色信息
            roleMapper.deleteRoleUser(roleId);
            // 重置用户信息
            userMapper.initUserRole(list);
        }
        // 删除角色
        return roleMapper.deleteById(roleId)>0;
    }
}
